package com.chinackts.auth.service;

import com.chinackts.auth.model.HeaderStore;
import com.chinackts.auth.model.RdTime;
import com.chinackts.auth.repository.redis.HeaderStoreRepository;
import com.chinackts.auth.repository.redis.RdTimeRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lianhong
 * @since 2021/10/28
 */
@Service
public class HeaderStoreService {

    @Resource
    private HeaderStoreRepository headerStoreRepository;
    @Resource
    private RdTimeRepository rdTimeRepository;

    private static final String HEADER_NAME = "rdtime";

    /**
     * 添加报文头
     */
    public void addHeader(String id, String key, String value) {
        this.headerStoreRepository.setHeader(id, new HeaderStore(key, value));
    }


    /**
     * 响应码-30001，添加请求头（加签字符串）
     *
     * @param sign 加签字符串
     */
    public void addHeader_30001(String id, String sign) {
        List<HeaderStore> headers = new ArrayList<>();
        headers.add(new HeaderStore("sign", sign));
        headers.add(new HeaderStore("isVerify", "1"));
        this.headerStoreRepository.setHeaders(id, headers);
    }

    /**
     * 移除请求头中的加签字符串
     */
    public void removeHeader_30001(String id) {
        this.headerStoreRepository.deleteHeaders(id, "sign", "isVerify");
    }


    public void setRdTimeHeader(String id, RdTime rdTime) {
        String rt = this.rdTimeRepository.getRdTime(id, rdTime);
        if (StringUtils.isBlank(rt)) return;
        this.addHeader(id, HEADER_NAME, rt);
    }
}